<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showFailToast, closeToast } from 'vant'

//数据
interface HealthArticle {
  columnId: number
  columnName: string
  consultationMing: string
  introduction: string
  doctorId?: number
  spleen?: string
  anticancer?: string
  beneficial?: string
  function?: string
  likes?: number
  views?: number
}

interface ApiResponse {
  mes: string
  code: number
  data: HealthArticle[]
}

const router = useRouter()
const activeTab = ref(0)
const articles = ref<HealthArticle[]>([])
const loading = ref(false)
const finished = ref(false)

// 分类标签（从后端数据动态获取）
const categories = ref<string[]>([])

// 从文章中提取唯一的分类名称
const extractCategories = (articles: HealthArticle[]): string[] => {
  return Array.from(new Set(articles.map(article => article.columnName).filter(Boolean)))
}

// 存储所有原始数据
const allArticles = ref<HealthArticle[]>([])

// 获取健康资讯数据
const fetchHealthArticles = async (categoryName?: string) => {
  try {
    loading.value = true

    const response = await fetch('http://localhost:5029/api/Health/ShowColumn', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('网络请求失败')
    }

    const result: ApiResponse = await response.json()

    if (result.code === 300 && result.data && result.data.length > 0) {
      // 保存所有原始数据
      allArticles.value = result.data

      // 从所有数据中提取唯一的分类名称（只提取有数据的分类）
      const uniqueCategories = extractCategories(allArticles.value)

      if (uniqueCategories.length > 0) {
        // 更新分类标签
        const oldActiveCategory = categories.value[activeTab.value]
        categories.value = uniqueCategories

        // 确定当前选中的分类
        let targetCategory = categoryName
        if (!targetCategory) {
          // 如果没有指定分类，尝试保持之前的分类，否则选择第一个
          if (oldActiveCategory && uniqueCategories.includes(oldActiveCategory)) {
            targetCategory = oldActiveCategory
            activeTab.value = uniqueCategories.indexOf(oldActiveCategory)
          } else {
            targetCategory = uniqueCategories[0]
            activeTab.value = 0
          }
        } else {
          // 如果指定了分类，找到对应的索引
          const categoryIndex = uniqueCategories.indexOf(targetCategory)
          if (categoryIndex >= 0) {
            activeTab.value = categoryIndex
          } else {
            // 如果指定的分类不存在，选择第一个
            targetCategory = uniqueCategories[0]
            activeTab.value = 0
          }
        }

        // 根据选中的分类过滤数据，只显示当前分类的数据
        articles.value = allArticles.value.filter(article => article.columnName === targetCategory)
      } else {
        // 没有分类数据
        categories.value = []
        articles.value = []
      }
    } else {
      // API返回失败或数据为空
      allArticles.value = []
      categories.value = []
      articles.value = []
      if (result.code !== 300) {
        showFailToast(result.mes || '获取数据失败')
      }
    }

    finished.value = true
  } catch (error) {
    console.error('获取健康资讯失败:', error)
    allArticles.value = []
    categories.value = []
    articles.value = []
    showFailToast('网络请求失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 切换分类
const handleTabChange = (index: number) => {
  if (index >= 0 && index < categories.value.length) {
    activeTab.value = index
    const categoryName = categories.value[index]

    // 从已加载的数据中过滤，只显示当前分类的数据
    if (allArticles.value.length > 0) {
      articles.value = allArticles.value.filter(article => article.columnName === categoryName)
    } else {
      // 如果没有数据，重新加载
      articles.value = []
      finished.value = false
      fetchHealthArticles(categoryName)
    }
  }
}

// 点击文章
const handleArticleClick = (article: HealthArticle) => {
  // 跳转到文章详情页，传递文章数据和医生ID
  router.push({
    name: 'health-detail',
    params: { id: article.columnId.toString() },
    query: {
      columnId: article.columnId.toString(),
      columnName: article.columnName,
      consultationMing: article.consultationMing,
      introduction: article.introduction,
      doctorId: article.doctorId ? article.doctorId.toString() : '1', // 传递doctorId，如果没有则默认1
      spleen: article.spleen || '',
      anticancer: article.anticancer || '',
      beneficial: article.beneficial || '',
      function: article.function || ''
    }
  })
}

onMounted(() => {
  fetchHealthArticles()
})
</script>

<template>
  <div class="health-column-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="健康资讯栏目" left-arrow fixed placeholder @click-left="router.back()">
      <template #right>
        <van-icon name="ellipsis" size="20" />
        <van-icon name="aim" size="20" style="margin-left: 12px;" />
      </template>
    </van-nav-bar>

    <!-- 分类标签 -->
    <div class="category-tabs">
      <div class="tabs-scroll">
        <div v-for="(category, index) in categories" :key="index" :class="['tab-item', { active: activeTab === index }]"
          @click="handleTabChange(index)">
          {{ category }}
        </div>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="article-list">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="() => { }">
        <div v-for="article in articles" :key="article.columnId" class="article-card"
          @click="handleArticleClick(article)">
          <div class="article-content">
            <div class="article-title">{{ article.consultationMing }}</div>
            <div v-if="article.introduction" class="article-intro">{{ article.introduction }}</div>
            <div class="article-tag">#{{ article.columnName }}</div>
            <div class="article-metrics">
              <span class="metric-item">
                <van-icon name="good-job-o" size="14" />
                <span>{{ article.likes || 0 }}</span>
              </span>
              <span class="metric-item">
                <van-icon name="eye-o" size="14" />
                <span>{{ article.views || 0 }}</span>
              </span>
            </div>
          </div>
          <div class="article-image">
            <div class="image-placeholder"></div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<style scoped>
.health-column-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

/* 分类标签 */
.category-tabs {
  background-color: #fff;
  padding: 12px 16px;
  border-bottom: 1px solid #ebedf0;
  position: sticky;
  top: 46px;
  z-index: 99;
}

.tabs-scroll {
  display: flex;
  gap: 16px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
}

.tabs-scroll::-webkit-scrollbar {
  display: none;
}

.tab-item {
  padding: 8px 20px;
  font-size: 15px;
  color: #969799;
  white-space: nowrap;
  cursor: pointer;
  border-radius: 20px;
  transition: all 0.3s;
  flex-shrink: 0;
}

.tab-item.active {
  color: #1989fa;
  background-color: #ecf9ff;
  font-weight: bold;
}

/* 文章列表 */
.article-list {
  padding: 12px 16px;
}

.article-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.article-card:active {
  transform: scale(0.98);
}

.article-content {
  flex: 1;
  padding-right: 12px;
  display: flex;
  flex-direction: column;
}

.article-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-intro {
  font-size: 13px;
  color: #969799;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-tag {
  font-size: 12px;
  color: #1989fa;
  margin-bottom: 12px;
  align-self: flex-start;
}

.article-metrics {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-top: auto;
}

.metric-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
}

.article-image {
  width: 100px;
  height: 80px;
  flex-shrink: 0;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #e8f4ff 0%, #c8e8ff 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  background-color: #fff;
}

:deep(.van-nav-bar__title) {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
}

:deep(.van-nav-bar__right) {
  display: flex;
  align-items: center;
}

/* 列表样式 */
:deep(.van-list__finished-text) {
  color: #969799;
  font-size: 14px;
  padding: 20px 0;
}

:deep(.van-loading) {
  padding: 20px 0;
}
</style>
